package com.ns.dcjh.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.king.zxing.util.CodeUtils;
import com.ns.dcjh.R;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.utils.ToastUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yxing.ScanCodeActivity;
import com.yxing.utils.BitmapUtils;
import com.yxing.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MyScanActivity extends ScanCodeActivity {

    private static final int ALBUM_QUEST_CODE = 0x010;

    private boolean isOpenFlash;

    ImageView btnClose;
    TextView btnGallery;
    TextView btnFlash;


    @Override
    public int getLayoutId() {
        return R.layout.activity_my_scan;
    }

    @Override
    public void initData() {
        super.initData();

        btnClose = findViewById(R.id.btnClose);
        btnGallery = findViewById(R.id.btnGallery);
        btnFlash = findViewById(R.id.btnFlash);


        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnFlash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isOpenFlash = !isOpenFlash;
                setFlashStatus(isOpenFlash);
            }
        });

        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toAlbum();
            }
        });

    }


    private void toAlbum() {
        new RxPermissions(this)
                .requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Permission>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Permission permission) {
                        if (permission.granted) {
                            Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(albumIntent, ALBUM_QUEST_CODE);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case ALBUM_QUEST_CODE:
                    //接收图片识别结果
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        Bitmap bitmap = BitmapUtils.decodeBitmapFromPath(photo_path, 600, 600, false);
                        String code = CodeUtils.parseCode(bitmap);
                        Log.e("Tag",String.format("识别结果： %s", code));
                        if (code == null||code.isEmpty()){
                            ToastUtils.info(this,"未识别该图片中的二维码，请重试");
                        }else {
                            MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_REQUEST_SCAN_SUCCESS);
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("code", code);
                            msgEvent.setExtras(jsonData);
                            EventBus.getDefault().post(msgEvent);

                            finish();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }


}